package com.itheima.tliasmanagement.filter;


import com.itheima.tliasmanagement.util.Constant;
import com.itheima.tliasmanagement.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
// @WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        // 拿到请求的地址
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        String requestURI = request.getRequestURI();
        // 判断是否是登录请求
        if(requestURI.indexOf("/login") >= 0){
            // 放行
            chain.doFilter(request, response);
            return;
        }
        // 从请求头中获取token
        String token = request.getHeader(Constant.TOKEN);
        if(!StringUtils.hasLength(token)){
            // 禁止访问，跳转到登录
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        // 校验token
        try{
            Claims claims = JwtUtils.parseJWT(token);
            // token是合法的
            // 放行
            chain.doFilter(request, response);
        }catch(Exception e){
            log.error(e.getMessage(), e);
            // 禁止访问，跳转到登录
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       // 初始化的时候，仅仅执行一次
        log.info("LoginFilter init");
    }

    @Override
    public void destroy() {
        // 销毁的时候，仅仅执行一次
        log.info("LoginFilter destroy");
    }
}
